.NET Core 中实现健康检查
The following article is from 全球技术精选 Author SpringLeee
(给DotNet加星标,提升.Net技能)
前言
.NET Core中提供了开箱即用的运行状况检查,首先,我将在.NET Core API应用程序中执行运行状况检查,接下来,我们将使用DbContext集成SQL Server或数据库的运行状况检查,最后是如何实现自定义服务的运行状况检查。
在ASP.NET Core中实现健康检查
要实现运行状况检查,您需要在项目中安装 Microsoft.AspNetCore.Diagnostics.HealthChecks 。
接下来,在ConfigureServices方法中添加运行状况检查中间件。
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
services.AddControllers();
}
然后修改Configure方法,使用中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health");
});
}
现在,准备工作完成,运行程序然后访问 /health, 将看到下边结果:
HealthCheckService
.NET Core提供了一个HealthCheckService类,我们可以把健康检查的放到我们的控制器中,就像这样:
public class HealthController : ControllerBase
{
private readonly ILogger<HealthController> _logger;
private readonly HealthCheckService _healthCheckService;
public HealthController(ILogger<HealthController> logger,
HealthCheckService healthCheckService)
{
_healthCheckService = healthCheckService;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var report = await _healthCheckService.CheckHealthAsync();
return report.Status == HealthStatus.Healthy ? Ok(report) :
StatusCode((int)HttpStatusCode.ServiceUnavailable, report);
}
}
现在,如果尝试访问/health,将看到相同的结果。
接下来,我们将实现数据库运行状态检查
EntityFramework Core 健康检查
首先,还是需要安装Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore到我们的项目中。
接下来,我们拿到数据库上下文,然后修改代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddApiVersioning();
}
然后,运行程序,现在访问 /health 返回的结果是这样:
IHealthCheck
一些情况下,默认的健康检查可能不满足我们的需求,那么可以继承 IHealthCheck 接口,自定义我们的健康检查的逻辑。
public class ApiHealthCheck : IHealthCheck
{
private readonly IHttpClientFactory _httpClientFactory;
public ApiHealthCheck(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
CancellationToken cancellationToken = default)
{
using (var httpClient = _httpClientFactory.CreateClient())
{
var response = await httpClient.GetAsync("https://your-api-service.endpoint");
if (response.IsSuccessStatusCode)
{
return HealthCheckResult.Healthy($"API is running.");
}
return HealthCheckResult.Unhealthy("API is not running");
}
}
}
然后修改代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddDbContextCheck<WeatherForecastDbContext>()
.AddCheck<ApiHealthCheck>("ApiHealth");
services.AddControllers();
}
然后,运行程序,访问 /health,结果如下:
- EOF -
WinForm调用摄像头扫码识别二维码关于时间和空间复杂度的优化心得分享(C# )
看完本文有收获?请转发分享给更多人
推荐关注「DotNet」,提升.Net技能
点赞和在看就是最大的支持❤️